<template>
  <VPage class="app-container">
    <template #left>
      <div class="left">
        <select-category-tree @node-click="handleNodeClick"></select-category-tree>
      </div>
    </template>
    <VTable ref="tableRef" v-bind="tableOptins">
      <template #form="{ form }">
        <el-input
          v-model="form.template_name"
          placeholder="模版名称"
          clearable
          class="!w-[160px]"
        />
        <el-select v-model="form.status" placeholder="状态" class="!w-[160px]" clearable>
          <el-option
            v-for="item in statusList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
        <select-personnel
          class="!w-[160px]"
          v-model="form.create_user"
        ></select-personnel>
        <VGroup>
          <el-select class="!w-[150px]" v-model="form.timeRange.type">
            <el-option
              v-for="item in timeOption"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
          <el-date-picker
            v-model="form.timeRange.value"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="max-width: 300px"
            :default-time="defaultTime()"
          />
        </VGroup>
      </template>
      <template #toolbar_btns>
        <VButton auth="/goods/basics/sales-attribute/add" type="primary" @click="open()"
          ><svg-icon icon-class="add_new" />新增</VButton
        >
        <VButton
          auth="/goods/basics/sales-attribute/enable"
          :loading="loadings.enable"
          @click="handleStatus('Enable')"
        >
          <svg-icon class="mr-1 base-text-color" icon-class="state_finish_enable" />
          启用</VButton
        >
        <VButton
          auth="/goods/basics/sales-attribute/diabled"
          :loading="loadings.disable"
          @click="handleStatus('Disable')"
        >
          <svg-icon
            class="mr-1 text-red-500"
            icon-class="state_finish_cover"
          />禁用</VButton
        >
        <VButton
          auth="/goods/basics/sales-attribute/delete"
          :loading="loadings.del"
          @click="del"
          ><svg-icon class="mr-1 base-red-color" icon-class="del" />删除</VButton
        >
      </template>
    </VTable>
  </VPage>
  <VLog
    ref="AttributeLog"
    class="dialogPublic"
    :api="queryAttributeLog"
    options="templateId"
  ></VLog>
  <ComModal ref="ComModalRef" :treeData="menuList" @query="query"></ComModal>
</template>
<script setup name="BasicsSales-attribute" lang="jsx">
import VLog from "@/components/VLog";
import VImage from "@/components/Image/index.vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { nextTick, ref, reactive } from "vue";
import {
  queryAttributeList,
  queryAttributeLog,
  attributeUpdateStatus,
  attributeDelete,
} from "./api/index.js";
import { getclassificationList, getOption } from "@/api/index.js";
import ComModal from "./components/ComModal";
import SelectCategoryTree from "@/components/SelectCategoryTree";
const tableRef = ref();
const tableOptins = reactive({
  treeConfig: {
    transform: true,
    rowField: "name",
    parentField: "id",
    lazy: true,
    hasChild: "hasChild",
    loadMethod({ row }) {
      return fetchChildListApi(row);
    },
  },
  rowConfig: { height: 52 },
  formConfig: {
    data: {
      template_name: "",
      status: "",
      attribute_class: [],
      create_user: "",
      timeRange: { type: "create_time", value: [], range: true },
    },
  },
  columns: [
    { type: "checkbox", width: "40" },
    {
      field: "id",
      title: "ID",
      width: "80",
    },
    {
      field: "template_name",
      title: "模版名称",
    },
    {
      field: "attribute_class_name",
      title: "产品分类",
    },
    {
      field: "status_cn",
      title: "状态",
      width: "85",
      slots: {
        default: ({ row }) => {
          return (
            <div class="flex items-center">
              {row.status == 0 ? (
                <svg-icon class="mr-1 base-text-color" icon-class="state_finish_enable" />
              ) : (
                <svg-icon class="mr-1 text-red-500" icon-class="state_finish_cover" />
              )}
              {row.status_text}
            </div>
          );
        },
      },
    },
    {
      field: "create_username",
      title: "添加人",
      width: 95,
    },
    {
      field: "create_time",
      title: "添加时间",
    },
    {
      title: "操作",
      width: "120",
      fixed: "right",
      slots: {
        default: ({ row }) => {
          return (
            <div class="table-option">
              <VButton
                auth="/goods/basics/sales-attribute/edit"
                type="primary"
                text
                class="mr-3"
                onClick={() => open(row.id)}
              >
                编辑
              </VButton>
              <el-link type="primary" underline={false} onClick={() => viewLog(row.id)}>
                {" "}
                日志
              </el-link>
            </div>
          );
        },
      },
    },
  ],
  proxyConfig: {
    seq: true,
    props: {
      result: "data",
      total: "total",
    },
    autoLoad: false,
    ajax: {
      query: async ({ page, form }) => {
        const res = await queryAttributeList({ ...form, ...page });
        return new Promise(function (resolve) {
          resolve({
            data: res.data,
            total: res.total,
          });
        });
      },
    },
  },
});

const data = reactive({
  menuList: [],
  rowId: null,
  searchId: null,
});
const { menuList } = toRefs(data);

//选中菜单树
const handleNodeClick = (data) => {
  nextTick(() => {
    tableRef?.value.setFormField("attribute_class", [data.id]);
    refresh();
  });
};

// 枚举类
// let options = reactive({})
// const fetchOption = () => {
//   getOption('brand').then((res) => {
//     options = res.data
//   })
// }

// onMounted(() => {
//   fetchOption()
// })

const timeOption = [{ label: "添加时间", value: "create_time" }];

const statusList = [
  {
    label: "启用",
    value: 0,
  },
  {
    label: "禁用",
    value: 1,
  },
];

const loadings = reactive({
  enable: false,
  disable: false,
  del: false,
});

// 新增
const ComModalRef = ref();
const open = (id) => {
  nextTick(() => {
    ComModalRef.value.open(id);
  });
};

const handleStatus = (status) => {
  const records = getSelectRow().map((i) => i.id);
  if (!isHandle()) return;
  status == "Enable" ? (loadings.enable = true) : (loadings.disable = true);
  attributeUpdateStatus({ ids: records, status })
    .then((res) => {
      refresh();
      ElMessage.success(res.message);
    })
    .finally(() => {
      status == "Enable" ? (loadings.enable = false) : (loadings.disable = false);
    });
};

//查看日志
const AttributeLog = ref();
const viewLog = (id) => {
  AttributeLog.value.open(id);
};

const del = () => {
  const records = getSelectRow().map((i) => i.id);
  if (!isHandle()) return;
  ElMessageBox.confirm("此操作将永久删除该项, 是否继续?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
    confirmButtonClass: "btnFalses",
  }).then(() => {
    loadings.del = true;
    attributeDelete({ ids: records })
      .then((res) => {
        refresh();
        ElMessage.success(res.message);
      })
      .finally(() => {
        loadings.del = false;
      });
  });
};

//获取已选中的行
const getSelectRow = () => {
  return tableRef?.value.$table.getCheckboxRecords();
};

const query = () => {
  tableRef?.value.query();
};

const refresh = () => {
  tableRef?.value.$table.commitProxy("query");
};

const isHandle = () => {
  const records = getSelectRow();
  return !records.length ? ElMessage.error("请先选择行!") && false : true;
};
</script>
<style scoped lang="scss">
.mr5 {
  margin-right: 5px;
}

.left {
  padding: 8px;
  margin-bottom: 55px;
}

:deep(.el-tree--highlight-current .el-tree-node.is-current > .el-tree-node__content) {
  background-color: transparent;

  .lable {
    color: #3487ff !important;
  }
}
</style>
